'usescript';

$(document).ready(function () {

    eval($("#page").next('script').text());

    var container = $("#detail-panel>div:first>div:nth-child(2) a:last").parent().parent();
    var config;
    //先去读取配置然后执行
    chrome.storage.local.get('config', function (item) {
        //拿到配置后再去执行
        config = item.config;
    });

    //定义一个按钮
    var buttons = [
        '<span class="dfs_button dfs_staus"><a href="javascript:void(0)" id="dfs_order_submit"> dfs168订单采集 </a></span>',
    ];
    //加入到页面里
    for (var i in buttons) {
        container.append(buttons[i]);
    }

    var interval = setInterval(function () {

        var order_sn = getUrl('biz_order_id');
        if(config && config.query_order_api && order_sn){
            clearInterval(interval);
            var query_order = {'url': config.query_order_api, 'method': 'get', 'dataType': 'json', 'data': {'order_sn':order_sn}};
            //查询
            chrome.runtime.sendMessage(query_order, function (response) {
                //成功响应
                if (response && response.code == 200 && response.data.state == 1) {
                    var order = response.data.data;

                    var submit = order.is_exists ? '<span class="dfs_submit_yes dfs_staus">dfs168已采集</span>' : '<span class="dfs_submit_no dfs_staus">dfs168未采集</span>';
                    container.append(submit);

                    var shipping = order.is_shipping ? '<span class="dfs_shipping_yes dfs_staus">dfs168已发货</span>':'<span class="dfs_shipping_no dfs_staus">dfs168未发货</span>';
                    container.append(shipping);
                }
            });
        }
    },1000);


    //点击同步按钮采集订单信息，并且弹出表单让管理员确认
    $("#dfs_order_submit").on('click', function () {

        if (typeof data === 'object' && typeof data.mainOrder === 'object') {
            return render(parse(data));
        }
        //不能提取数据时报错
        layer.open({
            title: '错误', content: '无法采集到订单信息！请联系开发人员进行升级！'
        });
    });

    //核对完成后提交表单
    $(document).on('click', '#dfs_submit', function () {
        //根据配置参数做出提示
        if (!config || !config.order_submit_api) {
            layer.open({title: '错误', content: '缺少接口地址的配置！', time: 2500});
            return false;
        }

        var validateGoodsId = true;
        var dumplicate = false;
        var ids = {};
        $(".dfs_goods_id").each(function () {
            var val = $.trim($(this).val());
            if (val) {
                typeof ids[val] == 'undefined' ? ids[val] = val : dumplicate = true;
            } else {
                validateGoodsId = false;
            }
            if($(this).data('error') == 1){
                validateGoodsId = false;
            }
        });

        //缺少商品id
        if (!validateGoodsId) {
            layer.open({title: '错误', content: '必须填写商城的商品ID！', time: 2500});
            return false;
        }
        //商品id重复
        if (dumplicate) {
            layer.open({title: '错误', content: '商城的商品ID不能重复！', time: 2500});
            return false;
        }

        var data = $(this).closest('form').serializeObject();

        var order_submit = {'url': config.order_submit_api, 'method': 'POST', 'dataType': 'json', 'data': data};

        chrome.runtime.sendMessage(order_submit, function (response) {

            if (!response || !response.code) {
                layer.open({title: '错误', content: '没有收到响应！', time: 2500});
                return false;
            }

            if (response.code != 200) {
                layer.open({title: response.code + '错误', content: response.msg, time: 2500});
                return false;
            }

            var json = response.data;
            console.log(json);
            if (json.state != 1) {
                layer.open({title: '错误', content: json.msg, time: 2500});
                return false;
            }
            layer.closeAll();
            layer.open({title: '提示', content: json.msg, time: 2500});
        });
    });


    $(document).on('blur', '.dfs_goods_id', function () {
        var that = $(this);
        var $id = that.val();
        var container = $(this).parent().parent().find('.dfs_goods');

        //根据配置参数做出提示
        if (!config || !config.query_goods_api) {
            layer.open({title: '错误', content: '缺少接口地址的配置！', time: 2500});
            return false;
        }

        var query_goods = {
            'url': config.query_goods_api,
            'method': 'get',
            'dataType': 'json',
            'data': {'goods_id': $id}
        };

        chrome.runtime.sendMessage(query_goods, function (response) {
            //成功响应
            if (response && response.code == 200 && response.data.state == 1) {
                var goods = response.data.data;
                var content = '';
                content += '<span style="color: orange">（' + (goods.is_package ? '套餐' : '单品') + '）</span>';
                content += '<span style="color: blue"><a target="_blank" href="' + goods.link + '">' + goods.goods_name + '</a></span>';
                content += '<span style="color: green">   ［' + goods.goods_stocks + '］  </span>';
                content += '<span style="color: purple">  ［￥' + goods.goods_price + '］  </span>';
                container.html('<div class="pure-u-24-24">' + content + '</div>');

                that.data('error',0);
            } else {
                that.data('error',1);

                container.html('<div class="pure-u-24-24"><span style="color: red">无效的商品ID</span></div>')
            }
        });

    });
});

//渲染出订单提取的表单
function render(data) {
    //做一个表单将订单信息填入进取
    //var html = JSON.stringify(data);

    var order_goods = '<div class="pure-g">';
    var submitable = false;
    for (var i in data.order_goods) {
        var g = data.order_goods[i];
        if (g.goods_state == '未发货') submitable = true;
        order_goods += '<div class="pure-g">';
        order_goods += '<div class="pure-u-3-24"><img src="' + g.goods_image + '" title="' + g.goods_name + '" style="width:40px;height:40px;margin:10px 20px;"><input name="order_goods[' + i + '][goods_name]" type="hidden" value="' + g.goods_name + '"></div>';
        order_goods += '<div class="pure-u-3-24"><label>商品id</label><input name="order_goods[' + i + '][goods_id]" type="text" class="pure-u-23-24 dfs_goods_id" value="' + g.goods_id + '"></div>';
        order_goods += '<div class="pure-u-5-24"><label>规格</label><input name="order_goods[' + i + '][goods_sku]" type="text" class="pure-u-23-24" value="' + g.goods_sku + '"></div>';
        order_goods += '<div class="pure-u-4-24"><label>单价</label><input name="order_goods[' + i + '][goods_price]" type="text" class="pure-u-23-24" value="' + g.goods_price + '"></div>';
        order_goods += '<div class="pure-u-3-24"><label>数量</label><input name="order_goods[' + i + '][goods_quantity]" type="text" class="pure-u-23-24" value="' + g.goods_quantity + '"></div>';
        order_goods += '<div class="pure-u-3-24"><label>优惠金额</label><input name="order_goods[' + i + '][goods_promotion]" type="text" class="pure-u-23-24" value="' + g.goods_promotion + '"></div>';
        order_goods += '<div class="pure-u-3-24"><label>状态</label><span style="margin: 0.25em 0.1em ;padding: 0.5em 0.7em;">' + g.goods_state + '</span><input type="hidden" name="order_goods[' + i + '][goods_state]" value="' + g.goods_state + '"></div>';
        order_goods += '<div class="pure-u-23-24 dfs_goods"></div>';
        order_goods += '</div>';
    }
    order_goods += '</div>';

    var html = [
        '<form class="pure-form pure-form-stacked" style="margin: 20px;">',
        '<input name="order_sn" type="hidden" value="' + data.order_sn + '">',
        '    <fieldset>',
        '        <legend>订单：' + data.order_sn + '</legend>',
        '        <div class="pure-g">',
        '        	<div class="pure-u-6-24">',
        '            	<label>买家淘宝id</label>',
        '            	<input name="buyer_id" type="text" class="pure-u-22-24" value="' + data.buyer_id + '">',
        '            	<span class="pure-form-message-inline"></span>',
        '            </div>',
        '		 	<div class="pure-u-6-24">',
        '            	<label>买家名</label>',
        '            	<input name="buyer_name" type="text" class="pure-u-22-24" value="' + data.buyer_name + '">',
        '            	<span class="pure-form-message-inline"></span>',
        '            </div>',
        '            <div class="pure-u-6-24">',
        '            	<label>下单时间</label>',
        '            	<input name="place_time" type="text" class="pure-u-22-24" value="' + data.place_time + '">',
        '            	<span class="pure-form-message-inline"></span>',
        '            </div>',
        '			<div class="pure-u-6-24">',
        '            	<label>支付时间</label>',
        '            	<input name="payment_time" type="text" class="pure-u-22-24" value="' + data.payment_time + '">',
        '            	<span class="pure-form-message-inline"></span>',
        '            </div>',
        '		</div>',
        '		 <div class="pure-g">',
        '            <div class="pure-u-6-24">',
        '            	<label>订单金额</label>',
        '            	<input name="order_amount" type="text" class="pure-u-22-24" value="' + data.order_amount + '">',
        '            	<span class="pure-form-message-inline"></span>',
        '            </div>',
        '			<div class="pure-u-6-24">',
        '            	<label>运费</label>',
        '            	<input name="shipping_fee" type="text" class="pure-u-22-24" value="' + data.shipping_fee + '">',
        '            	<span class="pure-form-message-inline"></span>',
        '            </div>',
        '            <div class="pure-u-6-24">',
        '            	<label>支付宝流水号</label>',
        '            	<input name="alipay_sn" type="text" class="pure-u-22-24" value="' + data.alipay_sn + '">',
        '            	<span class="pure-form-message-inline"></span>',
        '            </div>',
        '            <div class="pure-u-6-24">',
        '            	<label>邮政编码</label>',
        '            	<input name="post_code" type="text" class="pure-u-22-24" value="' + data.post_code + '">',
        '            	<span class="pure-form-message-inline"></span>',
        '            </div>',
        '		</div>',
        '		<div class="pure-g">',
        '            <div class="pure-u-6-24">',
        '            	<label>收货人姓名</label>',
        '            	<input name="receiver_name" type="text" class="pure-u-22-24" value="' + data.receiver_name + '">',
        '            	<span class="pure-form-message-inline"></span>',
        '            </div>',
        '			<div class="pure-u-6-24">',
        '            	<label>收货人手机</label>',
        '            	<input name="receiver_phone" type="text" class="pure-u-22-24" value="' + data.receiver_phone + '">',
        '            	<span class="pure-form-message-inline"></span>',
        '            </div>',
        '            <div class="pure-u-12-24">',
        '				<label>收货人地址</label>',
        '            	<input name="receiver_address" type="text" class="pure-u-23-24" value="' + data.receiver_address + '">',
        '            	<span class="pure-form-message-inline"></span>',
        '            </div>',
        '		</div>',
        '		<div class="pure-g">',
        '           <div class="pure-u-12-24">',
        '            	<label>买家备注</label>',
        '            	<input name="user_note" type="text" class="pure-u-23-24" value="' + data.user_note + '">',
        '            	<span class="pure-form-message-inline"></span>',
        '            </div>',
        '            <div class="pure-u-12-24">',
        '            	<label>卖家备注</label>',
        '            	<input name="seller_note" type="text" class="pure-u-23-24" value="' + data.seller_note + '">',
        '            	<span class="pure-form-message-inline"></span>',
        '            </div>',
        '		</div>',
        order_goods,
        submitable ? '<button class="pure-button pure-button-primary" type="button" id="dfs_submit" style="margin: 10px;">提交</button>' : '',
        '    </fieldset>',
        '</form>'
    ].join("");
    //弹出订单信息让管理员进行修改，完了之后可以提交
    layer.open({
        type: 1,
        title: '订单信息采集',
        offset: 'auto',
        closeBtn: 1,
        fixed: true,
        move: false,
        resize: false,
        skin: 'layui-layer-rim', //加上边框
        area: ['800px', '550px'], //宽高
        content: html
    });
}

//解析页面捕获到的data数据，提取出需要的信息
function parse(data) {
    var order = data.mainOrder;
    //订单对象初始化
    var orderObject = {
        order_sn: order.id,
        alipay_sn: '',
        place_time: '',
        payment_time: '',
        order_amount: parseFloat(order.payInfo.actualFee.value),
        shipping_fee: 0.00,
        buyer_id: order.buyer.id,
        buyer_name: order.buyer.name,
        receiver_name: '',
        receiver_phone: '',
        receiver_address: '',
        post_code: '',
        stateText: order.statusInfo.text,
        user_note: data.buyMessage ? data.buyMessage : '',
        seller_note: '',
        order_goods: [],
    };

    //订单信息
    var info = order.orderInfo.lines[1].content;
    for (var x in info) {
        switch (info[x].value.name) {
            case "支付宝交易号:":
                orderObject.alipay_sn = info[x].value.value;
                break;
            case "创建时间:":
                orderObject.place_time = info[x].value.value;
                break;
            case "付款时间:":
                orderObject.payment_time = info[x].value.value;
                break;
        }
    }

    //页签处理
    for (var i in data.tabs) {
        if (data.tabs[i].id === 'logistics') {
            var receiver = data.tabs[i].content.address;
            var receiver_info = receiver.split('，');
            orderObject.receiver_name = receiver_info[0];
            orderObject.receiver_phone = receiver_info[1];
            receiver_info.reverse();
            orderObject.receiver_address = receiver_info[1];
            orderObject.post_code = receiver_info[0];
        }
    }
    //订单商品的提取
    for (var j in order.subOrders) {
        var goods_promotion = [];
        var sub = order.subOrders[j];
        //如果有优惠就去提取优惠金额
        if (sub.promotionInfo.length > 0) {
            goods_promotion = getAmount(sub.promotionInfo[0].content[0].value)
        }
        var sku = sub.itemInfo.skuText[0].content;
        var goods_sku = [];
        for (h in sku) {
            goods_sku.push(sku[h].value.value);
        }
        var state = sub.tradeStatus[0].content;
        var so = {
            goods_id: '',
            goods_name: sub.itemInfo.title,
            goods_image: sub.itemInfo.pic,
            goods_price: parseFloat(sub.priceInfo),
            goods_promotion: goods_promotion.length > 0 ? parseFloat(goods_promotion[0]) : 0.00,
            goods_quantity: parseInt(sub.quantity),
            goods_state: state.length > 0 ? (typeof state[0].value == 'object' ? state[0].value.text : state[0].value) : '',
            goods_sku: goods_sku.join('，')
        };
        orderObject.order_goods.push(so);
    }

    //运费提取
    var tmp_str = '';
    for (var x in order.totalPrice) {
        tmp_str += order.totalPrice[x].content[0].value;
    }
    var tmp_arr = tmp_str.match(/(快递\:+\d+(\.\d+))/ig);
    if (tmp_arr.length > 0) {
        orderObject.shipping_fee = parseFloat(tmp_arr[0].replace(/快递:/, ""));
    }

    for (var a in data.operationsGuide) {
        var b = data.operationsGuide[a];
        if (b.lines) {
            for (var c in b.lines) {
                var d = b.lines[c];
                if (d.content[0] && d.content[1] && d.content[0].value == '标记：') {
                    orderObject.seller_note = d.content[1].value;
                }
            }
        }
    }
    console.log(data);

    return orderObject;
}

//提取字符串中的金额
function getAmount($string) {
    return $string.match(/\d+(\.\d+)/g);
}


$.fn.serializeObject = function () {
    var o = {};
    var a = this.serializeArray();
    $.each(a, function () {
        if (o[this.name] !== undefined) {
            if (!o[this.name].push) {
                o[this.name] = [o[this.name]];
            }
            o[this.name].push(this.value || '');
        } else {
            o[this.name] = this.value || '';
        }
    });
    return o;
};

function getUrl($name) {
    var url = document.location.toString();
    var arrObj = url.split("?");

    if (arrObj.length > 1) {
        var arrPara = arrObj[1].split("&");
        var arr;

        for (var i = 0; i < arrPara.length; i++) {
            arr = arrPara[i].split("=");

            if (arr != null && arr[0] == $name) {
                return arr[1];
            }
        }
        return "";
    }
    else {
        return "";
    }
}

